import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Scanner;

/**
 * @author yu
 * @date 2025年05月14日 19:49
 */
public class Main2{
    static int[][] map;
    static int n;

    static class Node implements Comparable<Node>{
        int x, y , cost;
        Node(int x, int y, int cost){
            this.x = x;
            this.y = y;
            this.cost = cost;
        }
        @Override
        public int compareTo(Node other){
            return Integer.compare(this.cost, other.cost);
        }
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        try {
            if(!sc.hasNextInt()){
                System.out.println("-2");
                return;
            }
            n = sc.nextInt();
            if(n <=0 || n > 100){
                System.out.println("-2");
                return;
            }

            map = new int[n][n];
            for(int i=0;i<n;i++){
                for(int j=0;j<n;j++){
                    if(!sc.hasNextInt()){
                        System.out.println("-2");
                        return;
                    }
                    map[i][j] = sc.nextInt();
                    if(map[i][j] < 0 || map[i][j] > 10){
                        System.out.println("-2");
                        return;
                    }
                }
            }
            int res = comMinStaina();
            System.out.println(res);
        }catch (Exception e) {
            System.out.println("-2");
        }
    }

    private static int comMinStaina(){
        int[][] dist = new int[n][n];
        for(int[] row : dist) Arrays.fill(row, Integer.MAX_VALUE);

        dist[0][0] = map[0][0];

        PriorityQueue<Node> pq = new PriorityQueue<>();
        pq.offer(new Node(0,0,map[0][0]));
        int[] dx = {0,1};
        int[] dy = {1,0};
         while (!pq.isEmpty()){
             Node cur = pq.poll();
             int x = cur.x;
             int y = cur.y;
             int cost = cur.cost;

             for(int d=0;d<2;d++){
                 int nx = x + dx[d];
                 int ny = y + dy[d];
                 if(nx >= 0 && nx <n && ny >=0 && ny < n){
                     int diff = Math.abs(map[nx][ny] - map[x][y]);

                     if(diff <= 1){
                         int newCost = cost + map[nx][ny];
                         if(newCost < dist[nx][ny]){
                             dist[nx][ny]=newCost;
                             pq.offer(new Node(nx,ny,newCost));
                         }
                     }
                 }
             }
         }


        int res = Integer.MAX_VALUE;
        for(int i=0;i<n;i++){
            res = Math.min(res, dist[i][n-1]);
        }
        return res == Integer.MAX_VALUE ? -1 : res;
    }
}